from sqlalchemy import UniqueConstraint
from app.extensions import db
from time import time


# 用户模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    openid = db.Column(db.String(32), unique=True, nullable=False)
    session_key = db.Column(db.String(32), nullable=False)
    join_time = db.Column(db.Integer, default=int(time()))
    # 发布的试题
    publish = db.relationship('Question', backref='user', lazy='dynamic')
    # 评论的试题
    evaluations = db.relationship(
        'Question',
        secondary='evaluation',
        lazy='dynamic',
        backref=db.backref('e_users', lazy='dynamic')
    )
    # 学习的试题
    studies = db.relationship(
        'Question',
        secondary='study',
        lazy='dynamic',
        backref=db.backref('s_users', lazy='dynamic')
    )


# 试题模型
class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 0表示是题目，其他表示是回复的题号
    reply_id = db.Column(db.Integer, default=0)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    kind_id = db.Column(db.Integer, db.ForeignKey('kind.id'))
    create_time = db.Column(db.Integer, default=int(time()))
    content = db.Column(db.String(256), nullable=False)


# 类型模型
class Kind(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    icon = db.Column(db.String(20), unique=True, default='xxx.jpg')


# 评价模型
class Evaluation(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    # 是否是赞：True表示赞，False表示踩
    is_praise = db.Column(db.Boolean, default=True)
    __table_args__ = (
        # user_id, question_id是组合唯一索引
        UniqueConstraint('user_id', 'question_id'),
    )


# 学习模型
class Study(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    # 是否学会：True表示已会，False表示不会
    is_got = db.Column(db.Boolean, default=True)
    study_time = db.Column(db.Integer, default=int(time()))
    __table_args__ = (
        # user_id, question_id是组合唯一索引
        UniqueConstraint('user_id', 'question_id'),
    )